package com.api.projects.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.api.apicommon.model.entity.InterfaceInfo;
import com.api.apicommon.model.entity.User;
import com.api.apicommon.model.entity.UserInterfaceInfo;
import com.api.apicommon.model.enums.InterfaceInfoStatusEnum;
import com.api.apisdk.client.ApiClient;
import com.api.apisdk.utils.SignUtils;
import com.api.projects.annotation.AuthCheck;
import com.api.projects.common.*;
import com.api.projects.constant.CommonConstant;
import com.api.projects.constant.UserConstant;
import com.api.projects.exception.BusinessException;
import com.api.projects.exception.ThrowUtils;
import com.api.projects.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.api.projects.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import com.api.projects.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.api.projects.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.api.projects.service.InterfaceInfoService;
import com.api.projects.service.UserInterfaceInfoService;
import com.api.projects.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.naming.Name;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口
 *
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;
    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;
    private final static Gson gson = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param InterfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest InterfaceInfoAddRequest, HttpServletRequest request) {
        if (InterfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceinfo = new InterfaceInfo();
        BeanUtils.copyProperties(InterfaceInfoAddRequest, interfaceinfo);
        //校验名称  对添加的interfaceInfo进行校验，
        //TODO 如果有机会也可以想想怎么对接口进行校验
        interfaceInfoService.validInterfaceInfo(interfaceinfo, true);
        //TODO 这时候就需要对用户的信息进行校验了
        User loginUser = userService.getLoginUser(request);
        //经过一系列的校验之后就可以保存用户信息了
        interfaceinfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceinfo);
        if(!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceinfo.getId();
        //返回用的interfaceinof的id
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if(oldInterfaceInfo == null){
            //说明没有发现该接口信息
            throw new BusinessException( ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param InterfaceInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest InterfaceInfoUpdateRequest) {
        if (InterfaceInfoUpdateRequest == null || InterfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo InterfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(InterfaceInfoUpdateRequest, InterfaceInfo);

        // 参数校验
        interfaceInfoService.validInterfaceInfo(InterfaceInfo, false);
        long id = InterfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if(oldInterfaceInfo == null){
            throw   new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean result = interfaceInfoService.updateById(InterfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(Long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 返回interfaceinfo的list信息
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     * 只能管理员调用
     *
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceinfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest,HttpServletRequest request){
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        if(interfaceInfoQueryRequest != null){
            BeanUtil.copyProperties(interfaceInfoQueryRequest,interfaceInfo);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfo);
        List<InterfaceInfo> list = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(list);
    }
    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        //
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }

    /**
     * 接口上线（发布）操作，只允许管理员进行操作
     * @param idRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/online")
    public BaseResponse<Boolean> onlineInterface(@RequestBody IdRequest idRequest,HttpServletRequest request){
        //判断
        if(idRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        //判断接口信息是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if(oldInterfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //TODO  需要判断接口是否可用  使用apiClientsdk调用
        //只有管理员可以操作
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean b = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(b);
    }
    /**
     * 接口上线下线操作，只允许管理员进行操作
     * @param idRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/offline")
    public BaseResponse<Boolean> offlineInterface(@RequestBody IdRequest idRequest,HttpServletRequest request){
        //判断
        if(idRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        //判断接口信息是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if(oldInterfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //只有管理员可以操作
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean b = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(b);
    }

    /**
     * 接口测试调用
     * @param interfaceInfoInvokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,HttpServletRequest request){
        //判断请求参数是否存在
        if(interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取id
        Long id = interfaceInfoInvokeRequest.getId();
        //获取请求参数
        String userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        //判断接口信息是否存在
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        //如果不存在
        if(interfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //TODO 需要判断接口请求参数是否正确
        boolean b = interfaceInfoService.validRequestParms(interfaceInfo.getRequestParams(), userRequestParams, gson);
        if(!b){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"调用接口请求参数有问题，请检查后调用");
        }
        //存在拿到用户信息
        User loginUser = userService.getLoginUser(request);
        if(loginUser == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户信息不存在");
        }
        //校验用户信息和接口信息之后，从接口中拿到有效接口id和用户id
        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        userInterfaceInfo.setInterfaceinfoid(id);
        userInterfaceInfo.setUserid(loginUser.getId());
        //TODO  从用户接口信息表中获取接口新
        userInterfaceInfoService.validUserInterfaceInfo(userInterfaceInfo,true);
        // 校验之后说明可以调用了，使用sdk进行调用
        ApiClient apiClient = new ApiClient(loginUser.getAccessKey(),loginUser.getSecretKey());
        //String body = "{\"name\":\"zhangsan\"}";
        String res = getResult(interfaceInfo.getMethod(),interfaceInfo.getUrl(),userRequestParams,apiClient);
        try{
            Map map = gson.fromJson(res, Map.class);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"调用失败,请求检查后重试");
        }
        return ResultUtils.success(res);
    }
    private String getResult(String method,String url,String params,ApiClient apiClient){
        String result = "";
        if("post".equals(method)){
           result  = apiClient.getPostUrl(url,params);
        }else if("get".equals(method)){
           result  = apiClient.getGetUrl(url,params);
        }
        return result;
    }
}
